<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      fullscreen
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改调拨单信息' : '添加调拨单信息'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.swapNo!='' && form.swapNo!=null" style="width: 30%;color:var(--color-primary)" >调拨单号:{{ form.swapNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24">
            <el-form-item label="出库仓库:" prop="outWareHouseId">
              <el-select  v-model="form.outWareHouseId" filterable placeholder="请选择出库仓库" style="width:100%" @change="changeOutWarehouse">
                <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="入库仓库:" prop="inWareHouseId">
              <el-select  v-model="form.inWareHouseId" filterable placeholder="请选择入库仓库" style="width:100%" @change="changeInWarehouse">
                <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="制单日期:"  prop="swapDate">
              <el-date-picker v-model="form.swapDate" type="date" placeholder="请输入制单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="制单人:" prop="operatorId">
              <el-select  v-model="form.operatorId" filterable placeholder="请选择制单人" style="width:100%" @change="selectoperate" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="调拨金额:"  >
              <el-input v-model="form.swapAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="18" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="1"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >产品列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="OpenProductList"  >选择产品 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%"  :height="tableHeight" :full-height="tableFullHeight" >
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column label="产品编号"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center"  >
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center">
              <template slot-scope="{ row }">
                  <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="调拨数量" align="center" width="100">
            <template slot-scope="{ row ,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                <el-input  v-model="row.qty"  placeholder="请输入调拨数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                  row.qty = row.qty.replace(/\.{2,}/g,'.');
                  row.qty = row.qty.replace(/^\./g,'');
                  row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="可用数量" align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;"  >
                <el-input  v-model="row.stockQty"   disabled />
              </el-form-item>
            </template>
          </el-table-column>
           <el-table-column label="成本单价(￥)" align="center" width="150">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;"  >
                  <el-input  v-model="row.costPrice" disabled   prefix-icon="el-icon-_rmb"   />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="金额" align="center" width="120">
            <template slot-scope="{ row }">
              <el-input  v-model="row.amount" disabled  prefix-icon="el-icon-_rmb"  />
            </template>
          </el-table-column>
          <!--<el-table-column label="供应商" align="center" width="150">
            <template slot-scope="{ row  }">
              <el-form-item label-width="10" style="margin-bottom:0;"  >
                <el-select  filterable disabled v-model="row.supplierId" placeholder="请选择供应商" class="ele-fluid" >
                  <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="行备注" align="center" width="250">
            <template slot-scope="{ row }">
              <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3">
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <div slot="footer">
     
      <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" >
        挂单
      </el-button>
      <el-button type="warning" v-show="this.btnIndex!=3 &&  form.status!=5" :loading="loading" @click="audit" >
        审核
      </el-button>
      <el-button type="danger" v-show="form.status==5"  @click="unAudit"   >
        反审核
      </el-button>
      <el-button @click="handleClose" >关闭</el-button>
    </div>
     <!-- 编辑弹窗 -->
     <productchooseList :data="current" :visible.sync="showProductList"  @callback="reloadItemList"/>
    </ele-modal>
  </template>
  <script>
   
   import productchooseList from './productchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { QueryThirdcompanyType } from '@/api/enummanger';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { AddSwaporder,UpdateSwaporder,QuerySwaporderById,AuitSwaporder,AnitSwaporder } from '@/api/inventory/swaporder';


    export default {
      name: 'SwaporderEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {productchooseList},
      data() {
        return {
          // 表单数据
          form: {createUser:'',createDate:'',items:[]},
          // 表单验证规则
          rules: {
            outWareHouseId: [{required: true,message: '请选择出库仓库',trigger: 'blur'}],
            inWareHouseId: [{required: true,message: '请选择入库仓库',trigger: 'blur'}],
            swapDate: [{required: true,message: '请选择制单日期',trigger: 'blur'}],
            operatorId: [{required: true,message: '请选择制单人',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            costPrice: [{required: true,message: '请输入成本单价',trigger: 'blur'}],
          },
          fixedHeight:true,
          current:null,
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          showProductList:false,
          defaultDate:new Date(),
          hbDatas:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
          QGCompanyDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 480px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 380px)' : null;
          return fh;
        },
      },
      //初始化数据
      mounted(){
        this.initData();
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdateSwaporder : AddSwaporder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}

          if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

          this.loading = true;
          AuitSwaporder(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
          });
        },

        unAudit(){
          this.loading = true;
          AnitSwaporder(this.form.id)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          QuerySwaporderById(id)
            .then((res) => {
              this.form = res; 
          });
        },

        selectoperate(val){
          let acc = this.accountDatas.find((v)=>{ return v.id == val });
          if(acc){
            this.form.operatorName = acc.name;
          }
        },

        OpenProductList(){
          if(this.form.outWareHouseId){
            this.showProductList =true;
            this.current = this.form;
          }else{
            this.$message.info("请选择出库仓库")
          }
        },

        changeOutWarehouse(val){

         if(this.form.inWareHouseId == val){
          this.$message.info('出库与入库不能为同一仓库');
          this.form.outWareHouseId = '';
          return;
         } 
        },

        changeInWarehouse(val){
          if(this.form.outWareHouseId == val){
            this.$message.info('出库与入库不能为同一仓库');
            this.form.inWareHouseId= '';
            return;
          } 
        },

        reloadItemList(orderData){

          orderData.map((item)=>{

            let product = this.form.items.find((d)=>{
              return d.productId == item.productId
            })
            if(product){
              this.$message.info('当前选择的产品'+product.productName+'在列表中已经存在');
              return;
            }else{

              this.form.items.push({
                supplierId:item.supplierId,
                stockId:item.id,
                unitId:item.unitId,
                qty:0,
                amount:0,
                costPrice:item.costPrice,
                stockQty:item.useQty,
                swapId:this.form.id,
                productId:item.productId,
                supplierDesc:item.supplierDesc,
                productCode:item.productCode,
                productName:item.productName,
                spc:item.spc,
                unitDesc:item.unitDesc,
              })
            }
          });

          this.setPurAmountTotal();
        },

        //设置金额
        setAmount(row,index){
          if(row.qty>row.stockQty){
            this.$message.error("调拨数量不能大于库存数量");
          }else{
           
            if(row.costPrice && row.qty!=null && row.qty!=undefined&& row.qty!='' ){
              let rq = parseFloat(row.qty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].amount = (rq * cp).toFixed(2);
              this.setPurAmountTotal();
            }
          }
        },


        //设置入库金额
        setPurAmountTotal(){
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            let amount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amount) },0);
            this.$set(this.form,'swapAmount',amount.toFixed(2))
          }
        },


        /* 删除 */
        remove(_row, index) {
          this.form.items.splice(index, 1);
          this.setPurAmountTotal();
        },
     
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },

        handleClose() {
          this.$emit('update:visible', false);
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={items:[]};
              this.isUpdate = false;
              let currentUser = getUser();
              this.$set(this.form,'swapDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
              let currentUser = getUser();
              this.form.operatorId = currentUser.accountId;
              this.form.swapDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>